﻿using System.Collections.Generic;
using System.Linq;
using Common.Dao;
using Common.Extension;
using Common.Model;
using Spider.Util;

namespace Script.Script
{
    public class BlockMappingScript
    {
        /// <summary>
        /// 处理
        /// </summary>
        public static void Run()
        {
            List<string> classifyBlock = ClassifyModelDao.GetClassifyBlock().ToList();
            Dictionary<string, string> dxwBlocks = DxwBlockDao.GetDxwBlock().Distinct(new BlockCompartor())
                .ToDictionary(n => n.BlockName, m => m.TopicName);
            foreach (var block in classifyBlock)
            {
                if (!dxwBlocks.ContainsKey(block))
                {
                    dxwBlocks.Add(block, "");
                }
            }
            var allTopics = MainTopicDao.GetAllTopics();

            var dictionary = new Dictionary<string,string>();
            dictionary.AddRange(dxwBlocks,true);
            foreach (var keyValuePair in dictionary)
            {
                foreach (var allTopic in allTopics)
                {
                    if((allTopic.MergeName + allTopic.TopicName).Contains(keyValuePair.Key) && string.IsNullOrEmpty(keyValuePair.Value))
                    {
                        if (dxwBlocks.ContainsKey(keyValuePair.Key))
                        {
                            dxwBlocks.Remove(keyValuePair.Key);
                        }
                        dxwBlocks.Add(keyValuePair.Key, allTopic.TopicName);
                    }
                }
            }

            List<DxwEvent> dxwEvents = DxwEventDao.GetEvents();
            Util.DxwBlockMapping(dxwEvents, dxwBlocks);

            dxwEvents = dxwEvents.Where(m => !string.IsNullOrEmpty(m.Block)).ToList();
            DxwEventDao.UpdateEventBlock(dxwEvents);

            List<News> news = NewsDao.GetAllNews();
            Util.DxwBlockMapping(news, dxwBlocks);
            NewsDao.UpdateBlockClassify(news);
        }
    }
}